package com.gitee.wsl.concurrent.executor.sample

import com.gitee.wsl.concurrent.executor.Executor
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.internal.SynchronizedObject
import kotlinx.coroutines.internal.synchronized

/**
 * A [WorkRunner] that immediately invokes the [Runnable] you post on the thread you
 * posted from.
 */
@OptIn(InternalCoroutinesApi::class)
class ImmediateExecutor : Executor {

    private val lock = SynchronizedObject()

    override var isDisposed: Boolean = false

    override fun dispose(): Unit =
        synchronized(lock) {
            isDisposed = true
        }

    override fun exec(runnable: Runnable):Unit = synchronized(lock) {
        if (isDisposed) return
        runnable.run()
    }
}
